package  com.sat.common.utils

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * Created by WenJack on 2018/4/22.
 */
class OkHttpUtils private constructor() {
    class TrustAllCerts : X509TrustManager {
        override fun checkClientTrusted(
            chain: Array<X509Certificate>,
            authType: String
        ) {
        }

        override fun checkServerTrusted(
            chain: Array<X509Certificate>,
            authType: String
        ) {
        }

        override fun getAcceptedIssuers(): Array<X509Certificate?> {
            return arrayOfNulls(0)
        }
    }

    private fun logMsg(msg: String) {}

    companion object {
        const val WRITE_TIME_OUT: Long = 20
        const val READ_TIME_OUT: Long = 20

        @Volatile
        private var mClient: OkHttpClient? = null
        var client: OkHttpClient?
            get() {
                if (mClient == null) {
                    mClient = newClient()
                }
                return mClient
            }
            set(mClient) {
                Companion.mClient = mClient
            }

        fun newBuilder(): OkHttpClient.Builder {
            return OkHttpClient.Builder()
                .writeTimeout(
                    WRITE_TIME_OUT,
                    TimeUnit.SECONDS
                )
                .readTimeout(
                    READ_TIME_OUT,
                    TimeUnit.SECONDS
                )

                .apply {
                    createSSLSocketFactory()?.run {
                        sslSocketFactory(this, TrustAllCerts())
                    }

                }
                .hostnameVerifier { s, sslSession -> true }
                .addInterceptor(HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
                    Log.d(
                        "OkhttpUtils",
                        message
                    )
                }).setLevel(HttpLoggingInterceptor.Level.BODY))
        }

        fun newClient(): OkHttpClient {
            return newBuilder().build()
        }

        private fun createSSLSocketFactory(): SSLSocketFactory? {
            var ssfFactory: SSLSocketFactory? = null
            try {
                val sc = SSLContext.getInstance("TLS")
                sc.init(
                    null,
                    arrayOf<TrustManager>(TrustAllCerts()),
                    SecureRandom()
                )
                ssfFactory = sc.socketFactory
            } catch (e: Exception) {
            }
            return ssfFactory
        }
    }
}